// Copyright 2024 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "CaeScreenshotPipeDataHandleThread.h"
#include "../cae_service/CaeSocketAgent.h"
#include "../cae_service/CaeEngineControl.h"
#include "../cae_service/CaeParamStorage.h"

CaeScreenshotPipeDataHandleThread::CaeScreenshotPipeDataHandleThread(CaeDataPipe* pipe) {
    m_threadStatus = CAE_THREAD_STATUS_NEW;
    m_screenshotData = pipe;
}

CaeScreenshotPipeDataHandleThread::~CaeScreenshotPipeDataHandleThread() {
    m_screenshotData->ClearPipeData();
    m_screenshotData = nullptr;
    m_threadStatus = CAE_THREAD_STATUS_EXIT;
}

void CaeScreenshotPipeDataHandleThread::Run() {
    char threadName[] = "ScreenshotPipeHandle";
    prctl(PR_SET_NAME, threadName);
    LOGI("CaeScreenshotPipeDataHandleThread run.");

    if (m_screenshotData == nullptr) {
        LOGE("Failed to run caeScreenshotPipeDataHandleThread, dataPipe is null.");
        return;
    }

    while (m_threadStatus == CAE_THREAD_STATUS_RUNNING) {
        CaePipeData *pipeData = m_screenshotData->GetPipeData();
        if (pipeData != nullptr && pipeData->GetLen() > 0) {
            if (m_sendHook != nullptr) {
                m_sendHook((void *) pipeData->GetBuffer(), pipeData->GetLen());
            }
            delete pipeData;
            pipeData = nullptr;
        }
        usleep(500000);
    }
    m_threadStatus = CAE_THREAD_STATUS_EXIT;
    LOGI("CaeScreenshotPipeDataHandleThread exit.");
}

void CaeScreenshotPipeDataHandleThread::SetScreenshotDataSendHook(const ScreenshotDataSendHook &hook) {
    m_sendHook = hook;
}
